package com.mcintyret.site.web.controller.journal;

import com.mcintyret.site.service.journal.TextEntryHelper;
import com.mcintyret.site.web.controller.journal.forms.TextEntryForm;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * User: mcintyret2
 * Date: 06/04/2012
 */

@Controller
public class TextEntryController extends BaseJournalController {

    @Resource
    private TextEntryHelper textEntryHelper;

    @RequestMapping(value = "/{origin}/add-entry", method = RequestMethod.POST)
    private String addTextEntryToJournal(
            @Valid TextEntryForm textEntryForm,
            BindingResult bindingResult,
            @PathVariable String origin) {

        String redirectUrl = "redirect:/" + origin;

        if (!bindingResult.hasErrors()) {
            int id = textEntryHelper.addNewTextEntryToJournal(textEntryForm);
            redirectUrl += "#text_entry_" + id;
        }
        return redirectUrl;
    }

    @RequestMapping("/{origin}/delete-text-entry")
    private String deleteTextEntry(
            @RequestParam("id") int textEntryId,
            @PathVariable String origin) {

        textEntryHelper.deleteTextEntryWithId(textEntryId);

        return "redirect:/" + origin;
    }
}
